<script>
import { priorityOptions } from "./constant";

export default {
  data() {
    return {
      formData: {
        title: "",
        description: "",
        priority: "normal",
      },
      options: priorityOptions,
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
      },
    };
  },
  props: {
    todo: {
      type: Object,
    },
  },
  emits: ["add-todo", "modify-todo"],
  created() {
    if (this.todo) {
      Object.assign(this.formData, this.todo);
    }
  },
  methods: {
    async addOrModifyTodo() {
      try {
        // 表单验证
        await this.$refs.form.validate();
        if (this.todo) {
          // 修改
          const { data } = await this.$request(`/todos/${this.todo.id}`, {
            method: "put",
            data: this.formData,
          });
          if (data.success) {
            this.$emit("modify-todo", data.todo);
          }
        } else {
          // 添加
          const { data } = await this.$request("/todos", {
            method: "post",
            data: this.formData,
          });
          if (data.success) {
            this.$emit("add-todo", data.todo);
          }
        }
      } catch {}
    },
  },
};
</script>
<template>
  <ElDialog>
    <ElForm ref="form" :model="formData" :rules="rules">
      <ElFormItem label="标题" prop="title">
        <ElInput v-model="formData.title" />
      </ElFormItem>
      <ElFormItem label="内容" prop="description">
        <ElInput v-model="formData.description" />
      </ElFormItem>
      <ElFormItem label="优先级">
        <ElSelect v-model="formData.priority">
          <ElOption
            v-for="priority in options"
            :label="priority.label"
            :value="priority.value"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="addOrModifyTodo"> 确定 </el-button>
      </div>
    </template>
  </ElDialog>
</template>
